﻿using System;
using System.Linq;
using Hjt212Parser;
using HpSocketIotGateway.Db.Code1st;
using log4net;

namespace HpSocketIotGateway.Facade
{
    public class BizSendData
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(BizSendData));

        public static void SendByShake()
        {
            try
            {
                using (var ctx = new GatewayContext())
                {
                    var items =
                        ctx.send_data//.Where(t => t.mn != null && t.mn.Equals(mn))
                                     // .Where(t => t.rtn_9014 == null || !t.rtn_9014.Contains("O"))
                            .Where(t => !t.is_sent)
                            .OrderBy(t => t.qn)
                            .Take(1000)
                            .ToList();
                    if (items == null || items.Count < 1) return;
                    Log.Info("Download cmds:"+items.Count);
                    foreach (var item in items)
                    {
                        bool sentSuccess = BufferFacade.SendMsgToClient(item.mn, item.send_string);
                        ThreadUtil.Sleep(3000);
                        item.rtn_9011 = sentSuccess?"ON":"OFF" ;
                        item.rtn_9012 = sentSuccess ? "ON" : "OFF";
                        item.rtn_9014 = sentSuccess ? "ON" : "OFF";

                        item.sent_time = DateTime.Now;
                        item.is_sent = true;
                    }
                    // }
                    ctx.SaveChanges();
                    Log.Info("Download cmds finished:" + items.Count);

                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        public static void SendOnlineByMn()
        {
            try
            {
                using (var ctx = new GatewayContext())
                {
                    var mns = BufferFacade.GetMNs();
                    var mnsStr = string.Join(",", mns.ToArray());

                    var items =
                        ctx.send_data.Where(t => mnsStr.Contains(t.mn))
                            .OrderBy(t => t.qn)
                            .Take(1000)
                            .ToList();
                    foreach (var item in items)
                    {
                        bool sentSuccess = BufferFacade.SendMsgToClient(item.mn, item.send_string);
                        ThreadUtil.Sleep(2000);
                        item.rtn_9011 = sentSuccess?"ON":"OFF";
                        item.rtn_9012 = sentSuccess ? "ON" : "OFF";
                        item.rtn_9014 = sentSuccess ? "ON" : "OFF";

                        item.sent_time = DateTime.Now;
                        item.is_sent = true;

                    }
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

    }
}

